package com.treasure.mall.biz.service.core.marketing.impl;

import com.treasure.mall.biz.base.RedisLocker;
import com.treasure.mall.biz.config.redis.RedisConstant;
import com.treasure.mall.biz.dto.user.ModifyBalanceDTO;
import com.treasure.mall.biz.entity.marketing.UserSubscribeRedPacketPO;
import com.treasure.mall.biz.remote.wx.WxTemplateMessageService;
import com.treasure.mall.biz.repository.marketing.UserSubscribeRedPacketRepository;
import com.treasure.mall.biz.service.core.marketing.UserSubscribeRedPacketService;
import com.treasure.mall.biz.service.core.user.UserService;
import com.treasure.mall.biz.service.core.user.WxSubscribeUserService;
import com.treasure.mall.zbq.common.RandomUtils;
import com.treasure.mall.zbq.common.ienum.log.AdvanceLogType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 *
 * <p>
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.biz.service.core.marketing.impl
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/8/31 1:59 下午
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * 
 */
@Slf4j
@Service
public class UserSubscribeRedPacketServiceImpl implements UserSubscribeRedPacketService {

    @Autowired
    private UserSubscribeRedPacketRepository repository;
    @Autowired
    private RedisLocker redisLocker;
    @Autowired
    private UserService userService;
    @Autowired
    private WxTemplateMessageService wxTemplateMessageService;
    @Autowired
    private WxSubscribeUserService wxSubscribeUserService;

    @Override
    public boolean checkUsed(Long userId) {
        UserSubscribeRedPacketPO packetPO = repository.findFirstByUserId(userId);
        if (packetPO == null) {
            return false;
        }
        return packetPO.isUsed();
    }

    /**
     * 获取关注红包
     * 逻辑：如果关注红包为0，表示没有红包领取，前端体现为关注公众号
     *
     * @param userId
     * @return
     */
    @Override
    public double getAmount(Long userId) {
        double redAmount;
        while (true) {
            String lockKey = RedisConstant.LOCK_KEY_SUBSCRIBE_RED_PACKET + userId;
            boolean locker = redisLocker.tryLock(lockKey, RedisConstant.LOCK_KEY_SUBSCRIBE_RED_PACKET, 10);
            if (locker) {
                try {
                    UserSubscribeRedPacketPO packetPO = repository.findFirstByUserId(userId);
                    if (packetPO == null) {
                        UserSubscribeRedPacketPO po = new UserSubscribeRedPacketPO();
                        po.setUserId(userId);
                        //如果关注了。则直设置为已领取
                        po.setUsed(wxSubscribeUserService.checkSubscribe(userId));
                        po.setCreateTime(LocalDateTime.now());
                        //取最小数量
                        po.setAmount(Double.valueOf(String.format("%.2f", RandomUtils.nextDoubleInSection(0.01, 2))));
                        repository.save(po);
                        redAmount = po.getAmount();
                    } else {
                        redAmount = packetPO.getAmount();
                    }
                } finally {
                    redisLocker.release(lockKey, RedisConstant.LOCK_KEY_SUBSCRIBE_RED_PACKET);
                }
                break;
            }
        }
        return redAmount;
    }

    /**
     * 设置用户关注公众号红包
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public void setUserSubscribeAmount(Long userId) {
        try {
            UserSubscribeRedPacketPO packetPO = repository.findFirstByUserId(userId);
            double amount = 0;
            if (packetPO != null && !packetPO.isUsed()) {
                amount = packetPO.getAmount();
            }
            if (amount > 0) {
                ModifyBalanceDTO dto = new ModifyBalanceDTO();
                dto.setAmount(BigDecimal.valueOf(amount));
                dto.setRemark("关注公众号红包奖励");
                dto.setLogType(AdvanceLogType.LOG_TYPE16);
                dto.setId(userId);
                userService.modifyBalance(dto);
                packetPO.setUsed(true);
                packetPO.setUpdateTime(LocalDateTime.now());
                repository.save(packetPO);
//                wxTemplateMessageService.sendSubscribeSuccessMessage(userId, true);
            } else {
//                wxTemplateMessageService.sendSubscribeSuccessMessage(userId, false);
            }
        } catch (Exception e) {
            log.error("设置用户关注公众号红包异常", e);
//            wxTemplateMessageService.sendSubscribeSuccessMessage(userId, false);
        }
    }
}
